package com.ljt.yupictureddd.infrastracture.manager.upload;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpStatus;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import com.ljt.yupictureddd.infrastracture.api.CosManager;
import com.ljt.yupictureddd.infrastracture.config.CosClientConfig;
import com.ljt.yupictureddd.infrastracture.exception.BusinessException;
import com.ljt.yupictureddd.infrastracture.exception.ErrorCode;
import com.ljt.yupictureddd.infrastracture.exception.ThrowUtils;
import com.ljt.yupictureddd.infrastracture.manager.upload.dto.file.UploadPictureResult;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.model.ciModel.persistence.ImageInfo;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import javax.annotation.Resource;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;


@Slf4j
@Service
@Deprecated
public class FileManager {

    @Resource
    CosClientConfig cosClientConfig;

    @Resource
    CosManager cosManager;


    /**
     * 上传图片
     * @param file
     * @param uploadPathPrefix
     * @return
     */
    public UploadPictureResult uploadPicture(MultipartFile file, String uploadPathPrefix) {
//        校验图片
        validatePicture(file);
//        图片上传地址
        String uuid = RandomUtil.randomString(16);
        String originalFilename = file.getOriginalFilename();
        String uploadFileName = String.format("%s_%s.%s", DateUtil.formatDate(new Date()), uuid,
                FileUtil.getSuffix(originalFilename));
        String uploadPath = String.format("/%s/%s", uploadPathPrefix, uploadFileName);
//        解析结果并且返回（这里直接复制FileController上传文件代码）
        File tempFile = null;
        try {
            tempFile = File.createTempFile(uploadPath, "");
            file.transferTo(tempFile);
//            上传图片文件后，调用了智能万象，就可可以直接拿到Result,拿到CiUploadResult
            PutObjectResult putObjectResult = cosManager.putPictureObject(uploadPath, tempFile);
//            Result一直一直拿，就可以那个腾讯云智能万象分析出的图片详情了（一定要打开腾讯云的智能万象）
            ImageInfo imageInfo = putObjectResult.getCiUploadResult().getOriginalInfo().getImageInfo();
            int width = imageInfo.getWidth();
            int height = imageInfo.getHeight();
//            计算宽高比
            double picScale = NumberUtil.round(width / 1.0 / height, 2).doubleValue();
//            填入数据去
            UploadPictureResult uploadPictureResult = new UploadPictureResult();
            uploadPictureResult.setUrl(cosClientConfig.getHost() + "/" + uploadPath);
            uploadPictureResult.setPicName(FileUtil.mainName(originalFilename));
            uploadPictureResult.setPicSize(FileUtil.size(tempFile));
            uploadPictureResult.setPicWidth(width);
            uploadPictureResult.setPicHeight(height);
            uploadPictureResult.setPicScale(picScale);
            uploadPictureResult.setPicFormat(imageInfo.getFormat());
//            返回可以访问的地址
            return uploadPictureResult;
        } catch (Exception e) {
            log.error("图片上传到文件存储失败", e);
            throw new RuntimeException(e);
        } finally {
//            最后一定要删除临时文件
            this.deleteTempFile(tempFile, uploadPath);
        }
    }

    /**
     * 删除临时文件
     * @param tempFile
     * @param uploadPath
     */
    private void deleteTempFile(File tempFile, String uploadPath) {
        boolean delete = tempFile.delete();
        if (!delete) {
            log.error("file delete error, filepath = {}", uploadPath);
        }
    }

    /**
     * 校验图片
     * @param multipartFile
     */
    private void validatePicture(MultipartFile multipartFile) {
//        判断空
        ThrowUtils.throwIf(multipartFile == null, ErrorCode.PARAMS_ERROR, "文件为空");
//        判断文件大小
        final long ONE_MB = 1024 * 1024;
        long size = multipartFile.getSize();
        ThrowUtils.throwIf(size > 2 * ONE_MB, ErrorCode.PARAMS_ERROR, "文件大小太大");
//        判断文件类型
        final List<String> fileType = Arrays.asList("png", "gif", "jpg", "webp", "jpeg");
        String suffix = FileUtil.getSuffix(multipartFile.getOriginalFilename());
        ThrowUtils.throwIf(!fileType.contains(suffix), ErrorCode.PARAMS_ERROR, "文件类型不对");

    }
//    TODO 通过URL上传图片
    /**
     * 通过URL上传图片
     * @param fileUrl
     * @param uploadPathPrefix
     * @return
     *
     * 我们是直接从上面的方法复制来的,TODO是标记哪里改了
     * 这里可以直接用模板方法(行为型设计模式)
     */
    public UploadPictureResult uploadPictureByUrl(String fileUrl, String uploadPathPrefix) {
        //        校验图片
//        TODO
        validatePicture(fileUrl);
//        图片上传地址
        String uuid = RandomUtil.randomString(16);
//        TODO
//        String originalFilename = file.getOriginalFilename();
        String originalFilename = FileUtil.mainName(fileUrl);

        String uploadFileName = String.format("%s_%s.%s", DateUtil.formatDate(new Date()), uuid,
                FileUtil.getSuffix(originalFilename));
        String uploadPath = String.format("/%s/%s", uploadPathPrefix, uploadFileName);
//        解析结果并且返回（这里直接复制FileController上传文件代码）
        File tempFile = null;
        try {
            tempFile = File.createTempFile(uploadPath, "");
//            TODO 现在文件
            HttpUtil.downloadFile(fileUrl, tempFile);
//            file.transferTo(tempFile);
//            上传图片文件后，调用了智能万象，就可可以直接拿到Result,拿到CiUploadResult
            PutObjectResult putObjectResult = cosManager.putPictureObject(uploadPath, tempFile);
//            Result一直一直拿，就可以那个腾讯云智能万象分析出的图片详情了（一定要打开腾讯云的智能万象）
            ImageInfo imageInfo = putObjectResult.getCiUploadResult().getOriginalInfo().getImageInfo();
            int width = imageInfo.getWidth();
            int height = imageInfo.getHeight();
//            计算宽高比
            double picScale = NumberUtil.round(width / 1.0 / height, 2).doubleValue();
//            填入数据去
            UploadPictureResult uploadPictureResult = new UploadPictureResult();
            uploadPictureResult.setUrl(cosClientConfig.getHost() + "/" + uploadPath);
            uploadPictureResult.setPicName(FileUtil.mainName(originalFilename));
            uploadPictureResult.setPicSize(FileUtil.size(tempFile));
            uploadPictureResult.setPicWidth(width);
            uploadPictureResult.setPicHeight(height);
            uploadPictureResult.setPicScale(picScale);
            uploadPictureResult.setPicFormat(imageInfo.getFormat());
//            返回可以访问的地址
            return uploadPictureResult;
        } catch (Exception e) {
            log.error("图片上传到文件存储失败", e);
            throw new RuntimeException(e);
        } finally {
//            最后一定要删除临时文件
            this.deleteTempFile(tempFile, uploadPath);
        }
    }

    private void validatePicture(String fileUrl) {
//        1.校验非空
        ThrowUtils.throwIf(StrUtil.isBlank(fileUrl),ErrorCode.PARAMS_ERROR,"文件地址为空");
//        2.校验URL格式
//        用java自带的URL对象来校验!!!!
        try {
            new URL(fileUrl);
        } catch (MalformedURLException e) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"文件URL格式不正确");
        }
//        3.校验URL协议

        ThrowUtils.throwIf(!fileUrl.startsWith("http://")  && !fileUrl.startsWith("https://"),
                ErrorCode.PARAMS_ERROR,"仅支持HTTP 或者 HTTPS协议的文件地址");
//        4.发送HEAD请求验证文件是否存在
        HttpResponse httpResponse =null;
        try {
            httpResponse = HttpUtil.createRequest(Method.HEAD, fileUrl).execute();
//        非正常返回,无需执行其他判断
            if (ObjUtil.notEqual(httpResponse.getStatus(), HttpStatus.HTTP_OK)){
                return;
            }
//        5.文件存在,文件类型校验
            String contentType = httpResponse.header("Content-Type");
//            这个字符串不为空,文件才校验,宽松一点校验
            if (StrUtil.isNotBlank(contentType)){
//                允许图片类型
                final  List <String> ALLOW_CONTENT_TYPES =
                        Arrays.asList("image/jpeg","image/jpg","image/png","image/webp");
                ThrowUtils.throwIf(!CollUtil.contains(ALLOW_CONTENT_TYPES,contentType),ErrorCode.PARAMS_ERROR,"文件类型错误");
            }
//        6.文件存在,文件大小的校验
            String contentLengthStr = httpResponse.header("Content-Length");
            if (StrUtil.isNotBlank(contentLengthStr)){
                try {
                    long contentLength = Long.parseLong(contentLengthStr);
                    final long ONE_MB = 1024*1024;
                    ThrowUtils.throwIf(contentLength > 2* ONE_MB, ErrorCode.PARAMS_ERROR,"文件大小不能超过2MB");
                } catch (NumberFormatException e) {
                    throw new BusinessException(ErrorCode.PARAMS_ERROR,"文件大小格式错误");
                }
            }
        } finally {
            if (httpResponse != null) {
                httpResponse.close();
            }
        }
    }

}
